<!DOCTYPE html>
<#import "/spring.ftl" as spring />
<html lang="en">
<head>
    <link rel="stylesheet" type="text/css" href="<@spring.url '/admin/bootstrap3/bootstrap.min.css'/>">
    <link rel="stylesheet" type="text/css" href="<@spring.url '/admin/bootstrap3/bootstrap-theme.min.css'/>">
    <link rel="stylesheet" type="text/css"
          href="<@spring.url '/admin/bootstrap3/bootstrapTable/bootstrap-table.min.css'/>">
    <link rel="stylesheet" type="text/css"
          href="<@spring.url '/admin/bootstrap3/bootstrap3-editable/css/bootstrap-editable.css'/>">
    <link rel="stylesheet" type="text/css" href="<@spring.url '/admin/miniNoty/style.css?v=1'/>">
    <link rel="stylesheet" type="text/css" href="<@spring.url '/admin/css/mycss.css'/>">

    <title>TPO</title>
    <style>
        .article-area span {
            margin: 10px;
        }

        .question-number {
            border: 2px solid #c5c5c5;
            margin: 5px;
            padding: 10px 15px;
            border-radius: 21px;
            background-color: #f1f1f1;
            color: black;
            box-shadow: 1px 4px 2px #888888;
        }

        .question-number:hover {
            border: 2px solid #43b2d2;
            margin: 5px;
            padding: 10px 15px;
            border-radius: 21px;
            background-color: white;
            color: #43b2d2;
            box-shadow: 1px 4px 2px #43b2d2;
        }

        .question-number-active {
            border: 2px solid #43b2d2;
            margin: 5px;
            padding: 10px 15px;
            border-radius: 21px;
            background-color: #7ed9ff !important;
            color: #000000;
            font-weight: bold;
            box-shadow: 0px 0px 0px #888888;
        }

        .unsaved {
            border: 2px dashed #ffb221 !important;
        }

        .unsaved:hover {
            border: 2px dashed #ffb221 !important;
        }

        .option-id {
            padding: 5px 7px;
            margin-right: -25px;
            border-bottom: 1px dashed #007ee2;
        }
        .options>table{
            margin-left: 0px !important;
        }

        .number {
            border: 2px solid #43b2d2;
            margin: 5px;
            padding: 10px 15px;
            border-radius: 21px;
            background-color: #bceaff !important;
            color: #000000;
            font-weight: bold;
            animation: myfirst 1s;
        }

        @-webkit-keyframes myfirst /* Safari and Chrome */
        {
            from {
                padding: 0px 0px;
                border: 1px solid #4cdeff;
                background-color: #effcff;
                font-size: 0px
            }
            to {
                padding: 10px 15px;
                border: 2px solid #43b2d2;
                background-color: #bceaff;
                font-size: 14px
            }
        }

        .options-container {
            border: 1px dashed #b7b5b5;
            border-radius: 4px;
            margin-top: 10px;
            padding-top: 5px;
            padding-right: 5px;
            background: #d2d2d2;
        }

        .options table {
            background-color: #fbfbfb;
        }

        .options table td, th {
            background-color: #fbfbfb;
        }

        .ckbox {
            width: 25px;
            height: 25px;

        }

        .cbx-cat {
            width: 16px;
            height: 16px;
            margin-left: 10px !important;
        }

        .input-option {
            border-top: 0px;
            border-left: 0px;
            border-right: 0px;
            border-bottom: 2px solid #bfbfbf;
            border-radius: 0px;
        }

        .clip {
            margin: 5px;
            padding: 10px;
        }

        .option-delete {
            color: red;
            border: 1px solid #ededed;
            padding: 10px;
        }

        .del-question-num {
            border: 1px solid #981a1a;
            background-color: #b70000;
            color: white;
            border-radius: 20px;
            padding: 5px 10px;
            margin: 0 5px;
            font-weight: bold;
            font-size: 14px;
            font-style: italic;
        }

        .success {
            animation: success-animation 3s;

        }

        @-webkit-keyframes success-animation /* Safari and Chrome */
        {
            from {
                box-shadow: 3px 3px 13px #02ce0f;
            }
            to {
                box-shadow: 0px 0px 0px #02ce0f;
            }
        }

        .th_input{
            padding: 0 2px !important;
        }
    </style>
</head>
<body>
<nav class="navbar navbar-inverse navbar-fixed-top">
    <div class="container">
        <div class="navbar-header">
            <button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#navbar"
                    aria-expanded="false" aria-controls="navbar">
                <span class="sr-only">Toggle navigation</span>
                <span class="icon-bar"></span>
                <span class="icon-bar"></span>
                <span class="icon-bar"></span>
            </button>
            <a class="navbar-brand" href="#">TPO Admin</a>
        </div>
        <div id="navbar" class="collapse navbar-collapse">
            <ul class="nav navbar-nav">
                <li><a href="<@spring.url '/admin/category/list'/>">分类</a></li>
                <li><a href="<@spring.url '/admin/article/list'/>">文章</a></li>
                <li class="active"><a href="javascript:void(0);">题目</a></li>
                <li><a href="<@spring.url '/admin/user'/>">用户</a></li>
            </ul>
        </div><!--/.nav-collapse -->
    </div>
</nav>

<div class="container-fluid">
    <div class="question-list-area clip well">
        <span>文章 [${article.id}] 【${article.nameCn}】 的题目：</span>

        <!-- Question list -->
        <span id="question_numbers"></span>

        <!-- add button -->
        <a class="btn btn-info" href="javascript:addQuestion();" style="margin-left: 15px">添加题目</a>

        <!-- delete button -->
        <span id="btn_question_delete" style="margin-left: 15px"></span>
    </div>
    <!-- question detail-->
    <div id="div_questionForm"></div>
</div>

<script src="<@spring.url '/admin/js/jquery-3.2.1.min.js'/>"></script>
<script src="<@spring.url '/admin/js/jquery.tmpl.js'/>"></script>
<script src="<@spring.url '/admin/bootstrap3/bootstrap.min.js'/>"></script>
<script src="<@spring.url '/admin/js/popper.min.js'/>"></script>
<script src="<@spring.url '/admin/miniNoty/jquery.mininoty.min.js'/>"></script>

<!-- 单选，多选，排序题 1个选项 -->
<script id="questionOptionTemplate" type="text/x-jquery-tmpl">
        <div class="form-group" style="margin-bottom: 5px;">
            <label class="col-sm-2 control-label"> <span class="option-id">{%= id%}</span></label>
            <div class="col-sm-10 options">
                <input type="text" class="input-option form-control" name="option" data-option-id="{%= id%}" value="{%= content%}">
            </div>
        </div>
</script>

<!-- 单选，多选，排序题 选项模板 -->
<script id="questionForNormalTypeOptionTemplate" type="text/x-jquery-tmpl">
    {%each(i,opt) option%}
        <div class="form-group" style="margin-bottom: 5px;">
            <label class="col-sm-2 control-label"> <span class="option-id">{%= opt.id%}</span></label>
            <div class="col-sm-10 options">
                <input type="text" class="input-option form-control" name="option" data-option-id="{%= opt.id%}" value="{%= opt.content%}">
            </div>
        </div>
    {%/each%}
</script>

<!-- 表格题 选项模板 -->
<script id="questionOptionForTableTypeTemplate" type="text/x-jquery-tmpl">
    <div class="form-group" style="margin-bottom: 5px;">
        <label class="col-sm-2 control-label"></label>
        <div class="col-sm-10 options">
            <table class="form-group table table-bordered" id="table_options">
                <tbody>
                    <tr>
                        <th style="width: 55%;">&nbsp;-&nbsp;</th>
                        {%each(i,col) option[0].columns%}
                            <th><input type="text" class="form-control" name="options" style="padding"0 0" value="{%= col.value%}"></th>
                        {%/each%}
                    </tr>

                    {%each(i,row) option[0].rows%}
                     <tr>
                        <td><input type="text" class="form-control" name="options" value="{%= row.value%}"></td>
                        {%each(i,col) option[0].columns%}
                            <td><input type="checkbox" value="{%= i+1%}" class="ckbox"></td>
                        {%/each%}
                    </tr>
                    {%/each%}
                </tbody>
            </table>
        </div>
    </div>
</script>

<!-- 题目详情模板 -->
<script id="questionFormTemplate" type="text/x-jquery-tmpl">
    <div class="question-detail clip well">
        <span class="number" id="currentQuestionNumber">{%= number%}</span>
        <form class="form-horizontal" >
            <input type="hidden" name="id" id="id" value="{%= id%}">
            <input type="hidden" name="scenario_id" id="scenario_id" value="{%= scenario_id%}">
            <div class="form-group">
                <label class="col-sm-2 control-label">题型</label>
                <div class="col-sm-10">
                    <select class="form-control" name="type" id="type" onchange="changeQuestionType()" data-old-type="{%= type%}">
                        <option value="1" {%if type == 1%} selected="selected"{%/if%}> 单选题 </option>
                        <option value="2" {%if type == 2%} selected="selected"{%/if%}> 多选题 </option>
                        <option value="3" {%if type == 3%} selected="selected"{%/if%}> 排序题 </option>
                        <option value="4" {%if type == 4%} selected="selected"{%/if%}> 表格题 </option>
                    </select>
                </div>
            </div>
            <div class="form-group">
                <label class="col-sm-2 control-label">问题</label>
                <div class="col-sm-10">
                    <input type="text" class="form-control" id="content_en" name="content_en" value="{%= content_en%}">
                </div>
            </div>
            <!--<div class="form-group" >-->
                <!--<label class="col-sm-2 control-label">问题（中文）（选填）</label>-->
                <!--<div class="col-sm-10">-->
                    <!--<input type="text" class="form-control" id="content_cn" name="content_cn" value="{%= content_cn%}">-->
                <!--</div>-->
            <!--</div>-->
            <div class="form-group"  style="margin-bottom: 5px;">
                <label class="col-sm-2 control-label">音频</label>
                <div class="col-sm-10">
                    <input type="file" class="form-control" id="audio_url" name="audio_url" value="{%= audio_url%}">
                    原音频URL：<span id="span_orig_audio_url">{%= audio_url%}</span>
                </div>
            </div>

            <div class="options-container">
                <div class="form-group">
                    <label class="col-sm-2 control-label">选项</label>
                    <div class="col-sm-10" id="div_option_operation">
                    {%if type != 4%}
                        <button type="button" class="btn btn-info" onclick="addOption();"><span class=" glyphicon glyphicon-plus"></span>添加一个选项</button> &nbsp;&nbsp;&nbsp;&nbsp;
                        <button type="button" class="btn btn-danger" onclick="removeOption();"><span class=" glyphicon glyphicon-minus"></span>删除最后一个选项</button>
                    {%else%}
                        <div class="btn-group" role="group">
                           <button type="button" class="btn btn-info" onclick="addRow();">行： <span class=" glyphicon glyphicon-plus"></span> </button>
                           <button type="button" class="btn btn-danger" onclick="removeRow();"><span class=" glyphicon glyphicon-minus"></span> </button>
                        </div>&nbsp;&nbsp;&nbsp;&nbsp;
                        <div class="btn-group" role="group">
                            <button type="button" class="btn btn-info" onclick="addColumn();">列： <span class=" glyphicon glyphicon-plus"></span> </button>
                            <button type="button" class="btn btn-danger" onclick="removeColumn();"><span class=" glyphicon glyphicon-minus"></span> </button>
                        </div>
                    {%/if%}
                    </div>
                </div>
                <div class="options" id="options">
                    {%if type != 4%}
                        {%each(i,opt) option%}
                            <div class="form-group" style="margin-bottom: 5px;">
                                <label class="col-sm-2 control-label"> <span class="option-id">{%= opt.id%}</span></label>
                                <div class="col-sm-10 options">
                                    <input type="text" class="input-option form-control" name="option" data-option-id="{%= opt.id%}" value="{%= opt.content%}">
                                </div>
                            </div>
                        {%/each%}
                    {%else%}
                        <div class="form-group" style="margin-bottom: 5px;">
                            <label class="col-sm-2 control-label"></label>
                            <div class="col-sm-10 options">
                                <table class="form-group table table-bordered" id="table_options">
                                    <tbody>
                                        <tr>
                                            <th style="width: 55%;">&nbsp;-&nbsp;</th>
                                            {%each(i,col) option[0].columns%}
                                                <th><input type="text" class="th_input form-control" name="options" value="{%= col.value%}"></th>
                                            {%/each%}
                                        </tr>

                                        {%each(i,row) option[0].rows%}
                                         <tr>
                                            <td><input type="text" class="form-control" name="options" value="{%= row.value%}"></td>
                                            {%each(i,col) option[0].columns%}
                                                <td><input type="checkbox" value="{%= i+1%}" class="ckbox"></td>
                                            {%/each%}
                                        </tr>
                                        {%/each%}
                                    </tbody>
                                </table>
                            </div>
                        </div>
                    {%/if%}
                </div>
            </div>

            <div class="form-group" style="margin-top: 19px;">
                <label class="col-sm-2 control-label">答案</label>
                <div class="col-sm-10">
                {%if type != 4%}
                    <input type="text" class="form-control" id="answer" name="answer" value="{%= answer%}">
                    (多个选项使用英文逗号分隔，如：1,2,3)
                {%else%}
                    <span class="form-control" > 直接在选项中选择正确答案</span>
                {%/if%}
                </div>
            </div>
            <div class="form-group">
                <label class="col-sm-2 control-label">题目解析</label>
                <div class="col-sm-10">
                    <textarea class="form-control" rows="5" id="analysis" name="analysis">{%= analysis%}</textarea>
                </div>
            </div>

            <div class="form-group" id="div_question_category">
                <label class="col-sm-2 control-label">题目所属分类</label>
                <div class="col-sm-10">
                    {%each(i,cat) questionCategoryList%}
                    <label>
                      <input class="cbx-cat" type="checkbox" {%each(i,cateId) questionCategoryIds%}{%if cat.id == cateId%}checked="checked" {%/if%}{%/each%}value="{%= cat.id%}">{%= cat.nameCn%}
                    </label>
                    {%/each%}
                </div>
            </div>

            <button class="btn btn-primary btn-lg" type="button" onclick="saveQuestion()"> 保 存 </button>
        </form>
    </div>
</script>

<script>
    var articleId = ${article.id};
    var questionCategoryList = ${questionCategoryList};
    console.log(questionCategoryList);
    var questionList;
    $(function () {
        // 加载题目
        loadQuestion(articleId);
    });

    // 加载题目，从服务器读取数据，然后刷新题目列表，然后调用回调函数
    function loadQuestion(articleId, callback) {
        $.ajax({
            type: "post",
            url: "/tpo/admin/question/list/" + articleId,
            success: function (result, status) {
                if (result.status == 200) {
                    //alert('成功!');
                    var html = "";
                    questionList = result.data;
                    for (var i = 0; i < questionList.length; i++) {
                        var question = questionList[i];
                        html += '<a class="question-number" href="javascript:void(0);" id="questionList_' + question.number + '" onclick="showQuestionDetail(this,' + i + ')">' + question.number + '</a>';
                    }
                    $("#question_numbers").empty().append(html);
                    if (callback) {
                        callback();
                    }
                    console.log(questionList);
                } else {
                    alert(result.message);
                }
            },
            error: function () {
                alert('加载题目失败!!!');
            }
        });

    }

    // 使用本地数据模型重新加载题目列表
    function localRefreshQuestionNumberUi() {
        var html = "";
        for (var i = 0; i < questionList.length; i++) {
            var question = questionList[i];
            var unsaved = "";
            if (question.unsaved) {
                unsaved = "unsaved";
            }

            var selected = "";
            if (i == questionList.length - 1) {
                selected = "question-number-active"
            }
            html += '<a class="question-number ' + unsaved + ' ' + selected + '" href="javascript:void(0);" onclick="showQuestionDetail(this,' + i + ')">' + question.number + '</a>';
        }
        $("#question_numbers").empty().append(html);
    }

    // 新增题目
    function addQuestion() {
        // 构建一个question对象，然后添加到questionList数组中。
        for (var i = 0; i < questionList.length; i++) {
            var q = questionList[i];
            if (q["unsaved"] && q["unsaved"] == true) {
                alert("请先保存第" + q["number"] + "题之后再添加题目。");
                return;
            }
        }

        var question = {};
        question["unsaved"] = true;
        question["questionCategoryList"] = questionCategoryList;
        question["questionCategoryIds"] = [];
        question["number"] = questionList.length + 1;
        question["type"] = 1;
        question["scenario_id"] = articleId;
        question["answer"] = [];
        question["option"] = [{id: 1, rows: Array(0), label: "A", columns: Array(0), content: ""},
            {id: 2, rows: Array(0), label: "B", columns: Array(0), content: ""},
            {id: 3, rows: Array(0), label: "C", columns: Array(0), content: ""},
            {id: 4, rows: Array(0), label: "D", columns: Array(0), content: ""}];
        questionList.push(question);

        // 重新加载题号列表
        localRefreshQuestionNumberUi();

        $("#div_questionForm").empty();
        $("#questionFormTemplate").tmpl(question).appendTo("#div_questionForm");

        // 更新删除按钮
        updateDeleteQuestionButton(question["number"]);
    }

    // 更新删除按钮
    function updateDeleteQuestionButton(questionNumber) {
        var btn_del_html = '<a class="btn btn-danger" href="javascript:deleteQuestion();">删除第<span class="del-question-num" id="del-question-num">' + questionNumber + '</span>题</a>';
        $("#btn_question_delete").empty().append(btn_del_html);
    }

    // 删除题目
    function deleteQuestion() {
        var question = getCurrentQuestionModelObj();
        if (question.unsaved) {
            loadQuestion(articleId, function () {
                $("#btn_question_delete").empty();
                $("#div_questionForm").empty();
            });
        } else {
            ajaxDeleteSubmit(question.id);
        }


    }

    // 编辑题目：点击题目编号，显示题目详情
    function showQuestionDetail(obj, questionIndex) {
        // 切换题目列表样式
        $(".question-number-active").removeClass("question-number-active");
        $(obj).addClass("question-number-active");

        // 渲染题目详情界面
        var question = questionList[questionIndex];// 不能用题号，应该用下标
        var answer = question["answer"];
        if (question.type != 4 && answer.indexOf("[") >= 0) {
            question["answer"] = answerToPlainString(answer);
        }
        question["option"] = eval(question["option"]);
        question["questionCategoryList"] = questionCategoryList;
        question["questionCategoryIds"] = eval(question["questionCategoryIds"]);
        $("#div_questionForm").empty();
        $("#questionFormTemplate").tmpl(question).appendTo("#div_questionForm");

        // 更新删除按钮
        updateDeleteQuestionButton(question["number"]);

        // 勾选表格题目的答案
        checkTableQuestionAnswer(question);
    }

    // 勾选表格题目的答案
    function checkTableQuestionAnswer(question){
        if(question.type ==4){
            var answers = eval(question.answer);//[{"id": 1,"result": [2]},...]
            console.log(answers);
            $("#table_options>tbody>tr").each(function(i,obj){
                if(i>0){
                    $(obj).find("td").each(function(j,td){
                        if(j>=0){
                            // 后面的列是选项
                            var _cbx = $(td).find("input[type='checkbox']");
                            var isChecked = _cbx.prop('checked');
                            // 如果该选项是答案，勾选
                            if(havaAnswer(answers,i,j)){
                                _cbx.attr("checked","checked");
                            }
                        }
                    });
                }
            });
        }
    }
    function havaAnswer(answers,questionNumber,optionNumber){
        var haveAnswer = false;
        var answerForQuestionNumber;
        for(var i=0;i<answers.length;i++){
            var answer = answers[i];
            if(answer.id == questionNumber){
                answerForQuestionNumber = answer;
                break;
            }
        }
        if(answerForQuestionNumber && answerForQuestionNumber.result){
            //[{"id": 1,"result": [2]},...]
            for(var i=0;i<answerForQuestionNumber.result.length;i++){
                var res = answerForQuestionNumber.result[i];
                if(res == optionNumber){
                    haveAnswer=true;
                    break;
                }
            }
        }
        return haveAnswer;
    }

    // 保存题目：新增或编辑后保存题目到服务器。ajax提交数据，需要手动格式内容，并且带文件上传
    function saveQuestion() {
        // 获取当前编辑的题目的Model
        var question = getCurrentQuestionModelObj();

        // 使用界面上的数据（有可能是用户修改过的数据），更新Question Model
        question = updateModelWithUserData(question);
        console.log(question);

        // 提交数据到服务器
        ajaxSaveSubmit(question);
    }

    // 获取当前编辑的题目的Model
    function getCurrentQuestionModelObj() {
        var currentQuestionNumber = $("#currentQuestionNumber").text();
        console.log("题号：" + currentQuestionNumber);
        var question = null;
        for (var i = 0; i < questionList.length; i++) {
            if (questionList[i].number == currentQuestionNumber) {
                question = questionList[i];
            }
        }
        return question;
    }

    // 使用用户（或许编辑过的）界面上的数据，更新Question Model，返回新的更新过的question对象
    function updateModelWithUserData(question) {
        question["id"] = $("#id").val();
        question["scenario_id"] = $("#scenario_id").val();
        question["content_en"] = $("#content_en").val();
        question["type"] = $("#type").val();
        question["analysis"] = $("#analysis").val();
        var cateIds = [];
        $("#div_question_category input[type=checkbox]:checked").each(function () {
            cateIds.push($(this).val() * 1);
        });
        var str_ids = JSON.stringify(cateIds);
        question["questionCategoryIds"] = str_ids;

        if($("#type").val() == 4){
            getTableTypeOptionsAndAnswers(question);
        }else{
            getNormalTypeOptionsAndAnswers(question);
        }

        return question;
    }

    // 读取界面上的单选、多选、排序题的选项和答案
    function getNormalTypeOptionsAndAnswers(question){
        console.log("getNormalTypeOptionsAndAnswers");
        var options = [];
        $(".options input[name='option']").each(function (i, obj) {
            var option = {};
            var option_id = $(obj).attr("data-option-id");
            option["id"] = option_id * 1;
            option["content"] = $(obj).val();
            option["rows"] = [];
            option["columns"] = [];
            option["label"] = getOptionLabelByOptionId(option_id);
            options.push(option);
        });
        question["option"] = JSON.stringify(options);
        question["answer"] = answerToArrayString($("#answer").val());
    }

    // 读取界面上的表格题选项和答案
    function getTableTypeOptionsAndAnswers(question) {
        //console.log("getTableTypeOptionsAndAnswers");
        var options = [];
        var option = {};
        var rows = [];
        var columns = [];

        var answers = [];
        $("#table_options>tbody>tr").each(function(i,obj){
            //console.log(i+"-->>"+obj)
            if(i==0){
                // columns
                $(obj).find("input").each(function(j,input){
                    var column = {};
                    column["id"] = j+1;
                    column["value"] = $(input).val();
                    columns.push(column);
                });
            }
            else{
                // rows
                var answer = {};
                answer["id"] = i;
                answer["result"] = [];
                $(obj).find("td").each(function(j,td){
                    if(j==0){
                        // 第1列是问题
                        var row = {};
                        row["id"] = i;
                        row["value"] = $(td).find("input").val();
                        rows.push(row);
                    }else{
                        // 后面的列是选项
                        var _cbx = $(td).find("input[type='checkbox']");
                        var isChecked = _cbx.prop('checked');
                        if(isChecked){
                            answer["result"].push(j);
                        }
                    }
                });
                // 答案
                answers.push(answer);
            }

        });

        option["columns"]=columns;
        option["rows"] = rows;
        options.push(option);

        question["option"] = JSON.stringify(options);
        question["answer"] = JSON.stringify(answers);
    }

    // ajax保存数据
    function ajaxSaveSubmit(question) {
        $.ajax({
            type: "post",
            url: "/tpo/admin/question/save/",
            contentType: "application/x-www-form-urlencoded",
            data: question,
            dataType: "json",
            success: function (res, status) {
                console.log(res);
                if (res.status == 200) {
                    $.miniNoty("保存成功", "success");
                    ajaxUpload(res.data);
                    loadQuestion(articleId);
                } else {
                    $.miniNoty("错误：" + res.message, "error");
                }
            },
            error: function () {
                $.miniNoty("错误", "error");
            }
        });
    }

    // ajax上传文件，如果没有文件不做任何操作。
    function ajaxUpload(questionId) {
        var file = $('#audio_url')[0].files[0];
        if (file) {
            var formData = new FormData();
            console.log(file);
            formData.append('file', file);
            $.ajax({
                url: '/tpo/admin/question/uploadAudio/' + questionId,
                type: 'POST',
                cache: false,
                data: formData,
                processData: false,
                contentType: false
            }).done(function (res) {
                if (res.status == 200) {
                    $('#audio_url').val("");
                    $("#span_orig_audio_url").empty().append(res.data);
                    $.miniNoty("音频上传成功", "success");
                } else {
                    $.miniNoty("音频上传失败:" + res.message, "error");
                }
            }).fail(function (res) {
                $.miniNoty("音频上传失败", "error");
            });
        }
    }

    // ajax删除数据
    function ajaxDeleteSubmit(questionId) {
        $.ajax({
            type: "get",
            url: "/tpo/admin/question/delete/" + questionId,
            dataType: "json",
            success: function (res, status) {
                if (res.status == 200) {
                    $.miniNoty("删除成功", "success");
                    loadQuestion(articleId);
                    $("#btn_question_delete").empty();
                    $("#div_questionForm").empty();
                } else {
                    $.miniNoty("音删除失败:" + res.message, "error");
                }
            },
            error: function () {
                $.miniNoty("音删除失败", "error");
            }
        });
    }

    // 改变题目类型
    function changeQuestionType() {
        var type = $("#type").val();
        var oldType = $("#type").attr("data-old-type");

        console.log("question type is: " + type + ", oldType is: " + oldType);
        if (type == 4 && !isEquType(type,oldType)) {
            initOptionUiForTableType();
        } else if (type != 4 && !isEquType(type,oldType)) {
            initOptionUiForNormalType();
        }
        $("#type").attr("data-old-type", type);
    }

    // 初始化一般题目的选项
    function initOptionUiForNormalType() {
//        questionForNormalTypeOptionTemplate
        var option = {"option":[{"id": 1, "rows": [], "label": "A", "columns": [], "content": ""}, {"id": 2, "rows": [], "label": "B", "columns": [], "content": ""}, {"id": 3, "rows": [], "label": "C", "columns": [], "content": ""}, {"id": 4, "rows": [], "label": "D", "columns": [], "content": ""}]};
        $("#options").empty();
        $("#questionForNormalTypeOptionTemplate").tmpl(option).appendTo("#options");

        var oper_html = '<button type="button" class="btn btn-info" onclick="addOption();"><span class=" glyphicon glyphicon-plus"></span>添加一个选项</button> &nbsp;&nbsp;&nbsp;&nbsp;\n' +
            '    <button type="button" class="btn btn-danger" onclick="removeOption();"><span class=" glyphicon glyphicon-minus"></span>删除最后一个选项</button>';
        $("#div_option_operation").empty().append(oper_html);


    }

    // 初始化表格题目的选项
    function initOptionUiForTableType() {
//        questionOptionForTableTypeTemplate
        var option = {"option":[{"rows": [{"id": 1, "value": ""}, {"id": 2, "value": ""}, {"id": 3, "value": ""}, {"id": 4, "value": ""}], "columns": [{"id": 1, "value": ""}, {"id": 2, "value": ""}]}]};
        $("#options").empty();
        $("#questionOptionForTableTypeTemplate").tmpl(option).appendTo("#options");


        var oper_html = ' <div class="btn-group" role="group">\n' +
            '                           <button type="button" class="btn btn-info" onclick="addRow();">行： <span class=" glyphicon glyphicon-plus"></span> </button>\n' +
            '                           <button type="button" class="btn btn-danger" onclick="removeRow();"><span class=" glyphicon glyphicon-minus"></span> </button>\n' +
            '                        </div>&nbsp;&nbsp;&nbsp;&nbsp;\n' +
            '                        <div class="btn-group" role="group">\n' +
            '                            <button type="button" class="btn btn-info" onclick="addColumn();">列： <span class=" glyphicon glyphicon-plus"></span> </button>\n' +
            '                            <button type="button" class="btn btn-danger" onclick="removeColumn();"><span class=" glyphicon glyphicon-minus"></span> </button>\n' +
            '                        </div>';
        $("#div_option_operation").empty().append(oper_html);
    }

    //------------------------------------------------------------------------------------------------------------------
    // 添加选项（界面操作，不涉及数据模型）
    function addOption() {
        // 获取当前编辑的题目的Model
        var optionId = $(".options input[name='option']").length + 1;
        if (optionId > 8) {
            alert("最多可以有8个选项");
            return;
        }
        var option = {id: optionId, content: ""};
        $("#questionOptionTemplate").tmpl(option).appendTo("#options");
    }

    // 删除最后一个选项（界面操作，不涉及数据模型）
    function removeOption() {
        $("#options>div:last").remove();
    }

    // -----------------------------------------------------------------------------------------------------------------
    // 表格题 添加一行
    function addRow() {
        var columnLength = $("#table_options>tbody>tr:first > th").length;
        var html_tr = '<tr>' +
            '<td><input type="text" class="form-control" name="options" value=""></th>';
        for (var i = 1; i < columnLength; i++) {
            html_tr += '<td><input type="checkbox" value="' + i + '" class="ckbox"></td>';
        }
        html_tr += '</tr>';
        $("#table_options>tbody").append(html_tr);
        console.log(columnLength);
        //console.log($("#table_options tr:first>td"));
    }

    // 表格题 移除一行
    function removeRow() {
        var rowLength = $("#table_options>tbody>tr").length;
        if (rowLength <= 2) {
            alert("至少有2行");
            return;
        }
        $("#table_options>tbody>tr:last").remove();
    }

    // 表格题 添加一列
    function addColumn() {
        var columnLength = $("#table_options>tbody>tr:first > th").length;
        $("#table_options>tbody>tr").each(function (i, obj) {
            if (i == 0) {
                var html_th = '<th><input type="text" class="th_input form-control" name="options" value=""></th>';
                $(obj).append(html_th);
            } else {
                var html_td = '<td><input type="checkbox" value="' + columnLength + '" class="ckbox"></td>';
                $(obj).append(html_td);
            }
        });
    }

    // 表格题 删除一列
    function removeColumn() {
        var columnLength = $("#table_options>tbody>tr:first > th").length;
        if (columnLength <= 2) {
            alert("至少有2行");
            return;
        }
        $("#table_options>tbody>tr").each(function (i, obj) {
            if (i == 0) {
                $(obj).find("th:last").remove();
            } else {
                $(obj).find("td:last").remove();
            }
        });
    }

    //-------------Util functions --------------------------------------------------------------------------------------
    //"[4,5]" ==>> "4,5"
    function answerToPlainString(answers) {
        //console.log(answers);
        var answer = eval(answers);
        var str = "";
        for (var i = 0; i < answer.length; i++) {
            if (i != (answer.length - 1)) {
                str += answer[i] + ",";
            } else {
                str += answer[i];
            }
        }
        return str;
    }

    function answerToArrayString(answers) {
        return "[" + answers + "]";
    }

    function getOptionLabelByOptionId(optionId) {
        var labels = ["A", "B", "C", "D", "E", "F", "G", "H"];
        if (optionId <= 0 || optionId > 8) {
            alert("无效的optionId：" + optionId + " ,有效的optionId为数字：1-8");
            return;
        }
        var label = labels[optionId - 1];
        return label;
    }

    // 是否是同类型的题目
    function isEquType(type, oldType) {
        if (type == 4 && oldType != 4) {
            return false;
        } else if (type != 4 && oldType == 4) {
            return false;
        } else {
            return true;
        }
    }
</script>
</body>
</html>